package com.liuheng.manager.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.liuheng.manager.mapper.SysMenuMapper;
import com.liuheng.manager.mapper.SysRoleMenuMapper;
import com.liuheng.manager.service.SysMenuService;
import com.liuheng.manager.utils.MenuHelper;
import com.liuheng.spzx.common.exception.CustomException;
import com.liuheng.spzx.model.entity.system.SysMenu;
import com.liuheng.spzx.model.vo.common.Result;
import com.liuheng.spzx.model.vo.common.ResultCodeEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/admin/system/sysMenu")
public class SysMenuController {
  @Autowired
  private SysMenuService sysMenuService;
  @Autowired
  private SysMenuMapper sysMenuMapper;
  @Autowired
  private SysRoleMenuMapper sysRoleMenuMapper;
  @GetMapping("/findAll")
    public Result findAll(){
    List<SysMenu> sysMenus = sysMenuMapper.selectList(null);
    List<SysMenu> tree = MenuHelper.getTree((ArrayList<SysMenu>) sysMenus);//要把数据转成vo传给前端
    return Result.build(tree, ResultCodeEnum.SUCCESS);
  }
  @PostMapping("/save")
  public Result save(@RequestBody SysMenu sysMenu){
    if (sysMenu.getParentId()!=null) {
      sysRoleMenuMapper.updateIsHalf(sysMenu.getParentId());
    }
    sysMenuService.save(sysMenu);
    return Result.build(null,ResultCodeEnum.SUCCESS);
  }
  @PutMapping("/update")
  public Result update( @RequestBody SysMenu sysMenu){
    sysMenuService.updateById(sysMenu);
    return Result.build(null,ResultCodeEnum.SUCCESS);
  }
  @DeleteMapping("/delete/{id}")
  public Result delete(@PathVariable Long id){
    LambdaQueryWrapper<SysMenu> wrapper = new LambdaQueryWrapper<>();
    wrapper.eq(SysMenu::getParentId,id);
    long count = sysMenuService.count(wrapper);
    if(count>0){
      throw new CustomException(ResultCodeEnum.NODE_ERROR);
    }else {
      sysMenuService.removeById(id);
    }
     return Result.build(null,ResultCodeEnum.SUCCESS);
  }
}
